<template>
  <div ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
const props = defineProps({
  MAXDATA: { type: Array, default: () => [] },
  yData: { type: Array, default: () => [] },
  xData: { type: Array, default: () => [] },
  barWidth: { type: Number, default: 4 } // 默认宽度，确保形状初始化时有值 
});

const chartRef = ref(null);
let chartInstance = null;

// 注册立方体左侧面形状（保持不变）
const CubeLeft = echarts.graphic.extendShape({
  shape: { x: 0, y: 0 },
  buildPath(ctx, shape) {
    const xAxisPoint = shape.xAxisPoint
    const c0 = [shape.x, shape.y]
    const c1 = [shape.x - props.barWidth, shape.y - props.barWidth]
    const c2 = [xAxisPoint[0] - props.barWidth, xAxisPoint[1] - props.barWidth]
    const c3 = [xAxisPoint[0], xAxisPoint[1]]
    ctx.moveTo(c0[0], c0[1]).lineTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).closePath()
  }
})

// 注册立方体右侧面形状（保持不变）
const CubeRight = echarts.graphic.extendShape({
  shape: { x: 0, y: 0 },
  buildPath(ctx, shape) {
    const xAxisPoint = shape.xAxisPoint
    const c1 = [shape.x, shape.y]
    const c2 = [xAxisPoint[0], xAxisPoint[1]]
    const c3 = [xAxisPoint[0] + props.barWidth * 2, xAxisPoint[1] - props.barWidth]
    const c4 = [shape.x + props.barWidth * 2, shape.y - props.barWidth]
    ctx.moveTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).lineTo(c4[0], c4[1]).closePath()
  }
})

// 注册立方体顶面形状（保持不变）
const CubeTop = echarts.graphic.extendShape({
  shape: { x: 0, y: 0 },
  buildPath(ctx, shape) {
    const c1 = [shape.x, shape.y]
    const c2 = [shape.x + props.barWidth * 2, shape.y - props.barWidth]
    const c3 = [shape.x + props.barWidth, shape.y - props.barWidth * 2]
    const c4 = [shape.x - props.barWidth, shape.y - props.barWidth]
    ctx.moveTo(c1[0], c1[1]).lineTo(c2[0], c2[1]).lineTo(c3[0], c3[1]).lineTo(c4[0], c4[1]).closePath()
  }
})

echarts.graphic.registerShape('CubeLeft', CubeLeft)
echarts.graphic.registerShape('CubeRight', CubeRight)
echarts.graphic.registerShape('CubeTop', CubeTop)

const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    const option = {
      backgroundColor: "#0f172a",
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: (params) => {
          const target = params.find((p) => p.value !== undefined);
          return target ? `${target.name}: ${target.value}` : '';
        },
        textStyle: { color: '#000', fontSize: 14 }
      },
      grid: {
        left: 20,
        right: 40,
        bottom: '19%',
        top: 107,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: props.xData,
        axisLine: { show: true, lineStyle: { color: 'white' } },
        offset: 20,
        axisTick: { show: false, length: props.barWidth, alignWithLabel: true, lineStyle: { color: '#7DFFFD' } },
        axisLabel: { fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        axisLine: { show: true, lineStyle: { color: 'white' } },
        splitLine: { show: false },
        axisTick: { show: false },
        axisLabel: { fontSize: 16 },
        boundaryGap: ['20%', '20%']
      },
      series: [
        // 2. 背景立方体系列：添加系列级动画配置
        {
          type: 'custom',
          // 系列动画配置（覆盖全局，可选）
          animationDuration: 1200,
          animationEasing: 'cubicOut',
          renderItem: function (params, api) {
            const location = api.coord([api.value(0), api.value(1)])
            // 3. 为每个形状添加动画过渡（关键）
            return {
              type: 'group',
              // 动画过渡属性：从y轴底部生长到目标高度
              transition: ['y', 'height'],
              children: [
                {
                  type: 'CubeLeft',
                  shape: {
                    api,
                    xValue: api.value(0),
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1],
                    xAxisPoint: api.coord([api.value(0), 0])
                  },
                  style: { fill: 'rgba(47,102,192,.27)' }
                },
                {
                  type: 'CubeRight',
                  shape: {
                    api,
                    xValue: api.value(0),
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1],
                    xAxisPoint: api.coord([api.value(0), 0])
                  },
                  style: { fill: 'rgba(59,128,226,.27)' }
                },
                {
                  type: 'CubeTop',
                  shape: {
                    api,
                    xValue: api.value(0),
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1],
                    xAxisPoint: api.coord([api.value(0), 0])
                  },
                  style: { fill: 'rgba(72,156,221,.27)' }
                }
              ]
            }
          },
          data: props.MAXDATA
        },
        // 4. 前景立方体系列：同样添加动画配置
        {
          type: 'custom',
          animationDuration: 1500,
          animationEasing: 'cubicOut',
          renderItem: (params, api) => {
            const location = api.coord([api.value(0), api.value(1)])
            return {
              type: 'group',
              transition: ['y', 'height'], // 动画过渡属性
              children: [
                {
                  type: 'CubeLeft',
                  shape: {
                    api,
                    xValue: api.value(0),
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1],
                    xAxisPoint: api.coord([api.value(0), 0])
                  },
                  style: {
                    fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#3B80E2' },
                      { offset: 1, color: '#49BEE5' }
                    ])
                  }
                },
                {
                  type: 'CubeRight',
                  shape: {
                    api,
                    xValue: api.value(0),
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1],
                    xAxisPoint: api.coord([api.value(0), 0])
                  },
                  style: {
                    fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#3B80E2' },
                      { offset: 1, color: '#49BEE5' }
                    ])
                  }
                },
                {
                  type: 'CubeTop',
                  shape: {
                    api,
                    xValue: api.value(0),
                    yValue: api.value(1),
                    x: location[0],
                    y: location[1],
                    xAxisPoint: api.coord([api.value(0), 0])
                  },
                  style: {
                    fill: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: '#3B80E2' },
                      { offset: 1, color: '#49BEE5' }
                    ])
                  }
                }
              ]
            }
          },
          data: props.yData
        },
        // 数据标签系列（保持不变）
        {
          type: 'bar',
          label: { normal: { show: false, position: 'top', formatter: (e) => props.yData[e.dataIndex] || '', fontSize: 16, color: '#fff', offset: [4, -25] } },
          itemStyle: { color: 'transparent' },
          data: props.MAXDATA
        }
      ]
    };

    chartInstance.setOption(option);

    // 窗口大小变化处理
    const handleResize = () => chartInstance && chartInstance.resize();
    window.addEventListener('resize', handleResize);
    onUnmounted(() => window.removeEventListener('resize', handleResize));
  }
};

watch(() => props.xData, (value) => {
  if (value) {
    chartInstance && chartInstance.dispose();
    initChart();
  }
},
  { immediate: true }
)

onMounted(() => initChart());
onUnmounted(() => chartInstance && chartInstance.dispose());
</script>

<style scoped lang="scss"></style>
